import { Button, Col, Input, Row, Swipe } from '@nutui/nutui-react-taro'
import { Image, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import clsx from 'clsx'
import { filter } from 'lodash'
import { autorun, toJS } from 'mobx'
import { useEffect, useRef, useState } from 'react'
import goodsBaseApi from 'src/api/goodsBaseApi'
import CustomHeader from 'src/components/CustomHeader/CustomHeader'
import MyEmpty from 'src/components/MyEmpty/MyEmpty'
import MyPopup from "src/components/MyPopup/MyPopup"
import MyScrollView from 'src/components/MyScrollView/MyScrollView'
import utils from 'src/utils/utils'
import { GoodsBaseData, MyDesignData } from 'types/type'
import toDesign from '../Design/designComponent/toDesign'
import styles from './myDesign.module.less'
import myDesignStore from './myDesignStore'

// 我的设计
export default function MyDesign() {

    const [list, setList] = useState<Array<MyDesignData>>(toJS(myDesignStore.list));
    const [isManaging, setIsManaging] = useState<boolean>(myDesignStore.isManaging);
    const [selectedIds, setSelectedIds] = useState<Array<number>>(myDesignStore.selectedIds);
    const [showSizePopup, setShowSizePopup] = useState(false); // 尺码弹窗显示状态
    const [selectedSize, setSelectedSize] = useState(''); // 当前选中的尺码
    const [sizes, setSizes] = useState<GoodsBaseData["data"]["sizes"]>([]); // 尺码选项列表
    const [currentDesignId, setCurrentDesignId] = useState(0); // 当前选中的设计ID
    const [currentProductNegativeId, setCurrentProductNegativeId] = useState(0); // 当前选中的底板ID

    // 标题编辑相关状态
    const [editingTitleId, setEditingTitleId] = useState<number | null>(null); // 当前正在编辑标题的设计ID
    const [editingTitleValue, setEditingTitleValue] = useState(''); // 编辑中的标题值
    const inputRef = useRef<any>(null); // 用于引用输入框并自动聚焦

    useEffect(() => autorun(() => {
        setList(toJS(myDesignStore.list));
        setSelectedIds(toJS(myDesignStore.selectedIds));
        setIsManaging(myDesignStore.isManaging);
    }, { delay: 30 }), []);

    // 当进入编辑状态时，自动聚焦输入框
    useEffect(() => {
        if (editingTitleId !== null && inputRef.current) {
            // 使用setTimeout确保DOM已经渲染完成
            setTimeout(() => {
                inputRef.current?.focus?.();
            }, 100);
        }
    }, [editingTitleId]);

    useDidShow(() => {
        myDesignStore.getNextPage(true);
    });

    const sysInfo = Taro.getSystemInfoSync();
    const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    const statusBarHeight = sysInfo.statusBarHeight || 0; // 状态栏高度
    const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2; // 导航栏总高度

    // // 计算每行的高度
    // const getGoodsItemHeight = () => {
    //     return 200 + (((230 - 200) / (430 - 375)) * (sysInfo.windowWidth - 375));
    // };

    // 显示尺码选择弹窗
    const showSize = (designId: number, currentSize: string) => {
        // 查找当前设计对应的底板ID
        const currentDesign = list.find(item => item.id === designId);
        if (currentDesign) {
            setCurrentDesignId(designId);
            setCurrentProductNegativeId(currentDesign.productNegativeId);
            setSelectedSize(currentSize);

            // 获取尺码选项
            goodsBaseApi.getProductNegativeById(currentDesign.productNegativeId).then((goodsBaseData) => {
                setSizes(goodsBaseData.data.sizes.filter(s => s.enable));
                setShowSizePopup(true);
            });
        }
    };

    // 显示颜色选择弹窗


    // 开始编辑标题
    const startEditTitle = (designId: number, currentTitle: string) => {
        setEditingTitleId(designId);
        setEditingTitleValue(currentTitle);
    };

    // 取消编辑标题
    const cancelEditTitle = () => {
        setEditingTitleId(null);
        setEditingTitleValue('');
    };

    // 确认修改标题
    const confirmEditTitle = (designId: number) => {
        // 查找当前设计
        const currentDesign = list.find(item => item.id === designId);
        if (currentDesign) {
            // 直接调用 store 的 updata 方法将修改提交到接口
            myDesignStore.updata({
                ...currentDesign,
                designName: editingTitleValue,
            });
        }

        // 重置编辑状态
        setEditingTitleId(null);
        setEditingTitleValue('');
    };

    return (
        <View className={styles.myDesign}>
            <CustomHeader title='我的设计' showBack />

            {
                list.length > 0 &&
                <View className={styles.manageButtons}>
                    <Button
                        size="small"
                        type="danger"
                        onClick={() => {
                            Taro.showModal({
                                title: '确认删除',
                                content: '确定要删除选中的设计吗？',
                                success: (res) => {
                                    if (res.confirm) {
                                        myDesignStore.delete()
                                    }
                                }
                            });
                        }}
                        className={clsx(styles.deleteBtn, isManaging ? styles.show : '')}
                    >
                        删除
                    </Button>
                    <Button
                        size="small"
                        type='primary'
                        onClick={() => myDesignStore.toggleManage()}
                    >
                        {isManaging ? '取消' : '管理'}
                    </Button>
                </View>
            }

            {list.length > 0 ? (
                <MyScrollView
                    style={{
                        height: sysInfo.windowHeight - navBarHeight - statusBarHeight - 100
                    }}
                    onScrollBottom={(e) => {
                        myDesignStore.getNextPage();
                    }}
                >
                    {
                        list.map((item, i) => {
                            // 是否过期商品，过期商品显示灰色样式提示信息
                            const isExpired =
                                item.productIfDel ||
                                item.productIfPutaway ||
                                item.productNegativeIfDel ||
                                item.productNegativeIfPutaway;

                            return (
                                <Swipe
                                    key={item.id}
                                    style={{
                                        background: 'none'
                                    }}
                                >
                                    <Row className={clsx(
                                        styles.cartItem,
                                        (!isManaging && isExpired) && styles.expiredItem
                                    )}>
                                        <Row
                                            onClick={() => {
                                                if (isManaging) {
                                                    myDesignStore.toggleSelect(item.id);
                                                } else {
                                                    // 非管理模式下点击跳转详情或其他操作
                                                }
                                            }}
                                        >
                                            <Col span={2} style={{ visibility: isManaging ? 'visible' : 'hidden' }}>
                                                <View
                                                    className={styles.itemRadio}
                                                    style={{ marginTop: '30px' }}
                                                >
                                                    <View className={clsx(styles.itemRadioInner, isManaging && selectedIds.includes(item.id) && styles.active)} >
                                                    </View>
                                                </View>
                                            </Col>
                                            <Col span={8} style={{ position: 'relative' }}>
                                                <Image
                                                    src={utils.ossSuffix(item.productDesign?.thumbs?.[0] || item.productShowImageUrl, 200)}
                                                    className={styles.itemImage}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        Taro.previewImage({
                                                            urls: filter(item.productDesign.thumbs).map(url => utils.ossSuffix(url, 1024)),
                                                        });
                                                    }}
                                                />
                                                {item.productDesign && item.productDesign.thumbs && item.productDesign.thumbs[1] && (
                                                    <View className={styles.thumbnailContainer}>
                                                        <Image
                                                            className={styles.thumbnailImage}
                                                            src={utils.ossSuffix(item.productDesign.thumbs[1], 100)}
                                                            onClick={(e) => {
                                                                e.stopPropagation();
                                                                e.preventDefault();
                                                                Taro.previewImage({
                                                                    urls: filter(item.productDesign.thumbs).map(url => utils.ossSuffix(url, 1024)),
                                                                });
                                                            }}
                                                        />
                                                    </View>
                                                )}
                                            </Col>
                                            <Col span={14} className={styles.itemDetails}>
                                                <View>
                                                    {editingTitleId === item.id ? (
                                                        <View className={styles.titleEditArea}>
                                                            <Input
                                                                className={styles.titleInput}
                                                                defaultValue={editingTitleValue}
                                                                maxLength={10}
                                                                ref={inputRef}
                                                                onChange={(value) => {
                                                                    setEditingTitleValue(value);
                                                                }}
                                                                onBlur={(e) => {
                                                                    // 失去焦点时确认编辑
                                                                    confirmEditTitle(item.id);
                                                                }}
                                                                onFocus={(e) => {
                                                                    // 预留拾取焦点事件
                                                                    console.log('Title input focused', item.id);
                                                                    // 这里可以添加获取焦点时的逻辑
                                                                }}
                                                                placeholder="请输入标题"
                                                            />
                                                        </View>
                                                    ) : (
                                                        <>
                                                            <View style={{ display: 'flex', alignItems: 'center' }}>
                                                                <Text className={styles.itemName}>{item.designName || item.productName}</Text>
                                                                <Text
                                                                    className={styles.modifyTitle}
                                                                    onClick={(e) => {
                                                                        e.stopPropagation();
                                                                        e.preventDefault();
                                                                        setEditingTitleValue(item.designName || item.productName);
                                                                        startEditTitle(item.id, item.designName || item.productName);
                                                                    }}
                                                                >
                                                                    修改
                                                                </Text>
                                                            </View>
                                                            <Text className={styles.itemInfo}>编号: UT{item.id}</Text>
                                                            {isExpired && <Text className={styles.expiredTag}>已过期</Text>}
                                                        </>
                                                    )}
                                                </View>

                                                {
                                                    item.productDesign && item.productDesign.color &&
                                                    <Text className={styles.itemInfo}>
                                                        颜色: {item.productDesign.color}
                                                    </Text>
                                                }
                                                <View className={styles.sizeButtonRow}>
                                                    <Text className={styles.itemInfo}>
                                                        尺码: {item.size || "均码"}
                                                        <Text
                                                            className={styles.uploadSize}
                                                            onClick={(e) => {
                                                                e.stopPropagation();
                                                                e.preventDefault();
                                                                showSize(item.id, item.size || '');
                                                            }}
                                                        >
                                                            修改
                                                        </Text>
                                                    </Text>
                                                    <Button
                                                        size="small"
                                                        className={styles.tryTemplateBtn}
                                                        disabled={isExpired}
                                                        onClick={async (e) => {
                                                            if (isExpired) return;
                                                            e.stopPropagation();
                                                            e.preventDefault();
                                                            await toDesign({
                                                                productId: item.productId,
                                                                productNegativeId: item.productNegativeId,
                                                                productDesign: item.productDesign,
                                                                designName: item.designName,
                                                                size: item.size,
                                                                color: item.productDesign?.color,
                                                                colorValue: item.productDesign?.colorValue,
                                                                needupload: true,
                                                            });
                                                        }}
                                                    >
                                                        使用模版
                                                    </Button>
                                                </View>
                                            </Col>
                                        </Row>
                                    </Row>
                                </Swipe>
                            )
                        })

                    }
                </MyScrollView>
            ) : (
                <MyEmpty
                    style={{
                        marginTop: "16vh"
                    }}
                    description="暂无设计"
                    actions={[
                        {
                            text: '去逛逛',
                            onClick: () => {
                                Taro.switchTab({
                                    url: '/pages/Category/Category'
                                })
                            }
                        }
                    ]}
                />
            )}

            {/* 尺码选择弹窗 */}
            <MyPopup
                open={showSizePopup}
                title={'选择尺码'}
                onClose={() => {
                    setShowSizePopup(false);
                }}
            >
                <View className={styles.title}>尺码</View>
                <View className={styles.sizeOptions}>
                    {sizes.map((size) => (
                        <Text
                            key={size.name}
                            className={clsx(styles.sizeOption, size.name === selectedSize && styles.selected)}
                            onClick={() => setSelectedSize(size.name)}
                        >
                            {size.name}
                        </Text>
                    ))}
                </View>

                <Button
                    type="primary"
                    block
                    className={styles.confirmButton}
                    onClick={() => {
                        // 查找当前设计
                        const currentDesign = list.find(item => item.id === currentDesignId);
                        if (currentDesign) {
                            // 创建更新后的设计数据
                            const updatedDesign = {
                                ...currentDesign,
                                size: selectedSize
                            };

                            // 调用 store 的 update 方法将完整数据传给接口
                            myDesignStore.updata(updatedDesign);
                        }

                        setShowSizePopup(false);
                    }}
                >
                    确定
                </Button>
            </MyPopup>



        </View>
    )
}